<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>拖拽</title>
    <style>
        html {
            position: relative;
        }
        body {
            margin: 0;
        }

        #img_container {
            position: absolute;
            width: 50px;
            height: 50px;
            top: 10px;
            left: 20px;
            background-color: rebeccapurple;
        }

        #img {}
    </style>
</head>

<body>
    <div id="img_container">
        <!-- <img id="img" src="yu.jpg" alt=""> -->
    </div>
    <script>
        window.addEventListener('DOMContentLoaded', () => {

            window.img = document.querySelector('#img_container');
            let clickX = 0, clickY = 0, initX = 0, initY = 0;
            let canBeRemove = false;

            const imgWidth = img.clientWidth;
            const imgHeight = img.clientHeight;
            const maxX = window.innerWidth - imgWidth;
            const maxY = window.innerHeight - imgHeight;
            img.addEventListener('mousedown', e => {
                const { pageX, pageY, offsetX, offsetY } = e;
                console.log(offsetX, offsetY);
                clickX = pageX;
                clickY = pageY;
                initX = img.offsetLeft;
                initY = img.offsetTop;
                canBeRemove = true;
            });
            document.addEventListener('mousemove', e => {
                if (!canBeRemove) { return; };
                const { pageX, pageY } = e;
                const x = pageX - clickX;
                const y = pageY - clickY;

                let moveX = initX + x;
                let moveY = initY + y;


                if (moveX < 1) {
                    moveX = 0;
                }
                if (moveX > maxX) {
                    moveX = maxX;
                }
                if (moveY < 1) {
                    moveY = 0;
                }
                if (moveY > maxY) {
                    moveY = maxY;
                }
                img.style = `top: ${moveY}px; left: ${moveX}px;`;
            });
            document.addEventListener('mouseup', e => {
                canBeRemove = false;
            });

        });
    </script>
</body>

</html>